﻿using Basic.FlowDAL;
using Basic.FlowModel.DB;
using Basic.FlowRemoteModel.NodeEvent.Model;
using WeDonekRpc.Helper;

namespace Basic.FlowCollect.lmpl
{
    internal class NodeEventCollect : INodeEventCollect
    {
        private readonly IFlowNodeEventDAL _BasicDAL;

        public NodeEventCollect ( IFlowNodeEventDAL basicDAL )
        {
            this._BasicDAL = basicDAL;
        }
        public DBFlowNodeEvent Get ( long id )
        {
            return this._BasicDAL.Get(id);
        }
        public bool Set ( NodeEventSet data )
        {
            DBFlowNodeEvent sour = this._BasicDAL.Find<DBFlowNodeEvent>(a => a.NodeId == data.NodeId && a.EventType == data.EventType);
            if ( sour == null )
            {
                this._BasicDAL.Add(data);
                return true;
            }
            else if ( data.EventId == 0 )
            {
                this._BasicDAL.Delete(sour.Id);
                return true;
            }
            return this._BasicDAL.Update(sour, data);
        }
        public void Clear ( long flowId )
        {
            long[] ids = this._BasicDAL.Gets(a => a.FlowId == flowId, a => a.Id);
            if ( !ids.IsNull() )
            {
                this._BasicDAL.Delete(ids);
            }
        }
        public void Clear ( long flowId, long nodeId )
        {
            long id = this._BasicDAL.Get(a => a.FlowId == flowId && a.NodeId == nodeId, a => a.Id);
            if ( id != 0 )
            {
                this._BasicDAL.Delete(id);
            }
        }
        public Result[] GetsByNode<Result> ( long nodeId ) where Result : class, new()
        {
            return this._BasicDAL.Gets<Result>(a => a.NodeId == nodeId);
        }
        public Result[] Gets<Result> ( long flowId ) where Result : class, new()
        {
            return this._BasicDAL.Gets<Result>(a => a.FlowId == flowId);
        }

        public void Delete ( DBFlowNodeEvent sour )
        {
            this._BasicDAL.Delete(sour.Id);
        }
    }
}
